<?php
/**
 * Created by ModelCreater.
 * Date: 2023-09-12
 * Time: 16:40:13
 */

namespace model;

use lib\common\CommonModel;
use lib\exception\ForbiddenException;
use lib\exception\NotFoundException;
use think\model\concern\SoftDelete;

class AdminUserModel extends CommonModel
{
    use SoftDelete;

    protected $table = 'admin_user';
    protected $deleteTime = 'delete_time';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $hidden = ['delete_time'];


    protected $schema = [
        'id'          => 'int',
        'username'    => 'string',
        'mobile'      => 'string',
        'email'       => 'string',
        'gender'      => 'int',
        'avatar'      => 'string',
        'password'    => 'string',
        'full_name'   => 'string',
        'post_name'   => 'string',
        'status'      => 'int',
        'login_time'  => 'datetime',
        'login_ip'    => 'string',
        'create_time' => 'datetime',
        'update_time' => 'datetime',
        'delete_time' => 'datetime',
    ];


    const ALLOWED_FIELDS = [
        'username', 'mobile', 'email', 'gender', 'avatar', 'password', 'full_name', 'post_name', 'status', 'login_time', 'login_ip',
    ];

    public function getLoginUser ($username) {
        $user = $this->where('username', $username)->find();
        if (empty($user)) {
            $user = $this->where('mobile', $username)->find();
        }
        if (empty($user)) {
            $user = $this->where('email', $username)->find();
        }
        return $user;
    }

    public function findUser ($id): AdminUserModel {
        $user = $this->where('id', $id)->hidden(['password'])->find();
        if (empty($user)) {
            throw new NotFoundException('用户信息不存在', 404001);
        }
        return $user;
    }
}
